﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities;
using Atmk.WaterMeter.MIS.Entities.Models;
using Atmk.WaterMeter.MIS.Services.DataAccess.Base;

namespace Atmk.WaterMeter.MIS.Services.DataAccess
{
    public class ProjectConfigurationRepository : BaseRepository, IProjectConfigurationRepository
    {
        /// <summary>
        /// 获取指定项目的配置信息，如果没有配置，则添加新的配置信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ParameterList GetConfiguration(string projectId)
        {
            using (var context = ContextBuilder.Build())
            {
                ParameterList result = null;
                if (context.ParameterList.FirstOrDefault(p => p.ProjectId == projectId)!=null)
                {
                    result = context.ParameterList.First(p => p.ProjectId == projectId);
                }
                else
                {
                    result = context.Add(new ParameterList() { ProjectId = projectId }).Entity;
                    context.SaveChanges();
                }
                return result;
            }
        }
        /// <summary>
        /// 修改配置信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="jsonConfig"></param>
        /// <returns></returns>
        public int UpdateConfig(string projectId, string jsonConfig)
        {
            using (var context = ContextBuilder.Build())
            {
                var config = GetConfiguration(projectId);
                config.Config = jsonConfig;
                context.ParameterList.Update(config);
                return context.SaveChanges();
            }
        }


    }
}